﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace OpenHardwareMonitor.GUI
{
    class UserOptionInt
    {
        private string name;
        private int value;
        private MenuItem menuItem;
        private event EventHandler changed;
        private PersistentSettings settings;

        public UserOptionInt(string name, int value,
          MenuItem menuItem, PersistentSettings settings)
        {

            this.settings = settings;
            this.name = name;
            if (name != null)
                this.value = settings.GetValue(name, value);
            else
                this.value = value;
            this.menuItem = menuItem;
            this.menuItem.Text = "Server Port";
            this.menuItem.Click += new EventHandler(menuItem_Click);
        }

        private void menuItem_Click(object sender, EventArgs e)
        {
            String port = "" + value;
            if (MainForm.InputBox("Network Port", "Port Number [1024,49151]:", ref port) == DialogResult.OK)
            {
                try
                {
                    int temp = int.Parse(port);

                    if(temp  < 1024) {
                        MessageBox.Show("Port must be >= 1024");
                    }
                    else if (temp > 49151)
                    {
                        MessageBox.Show("Port must be =< 49151");
                    }
                    else {
                        this.Value = temp;
                    }

                }
                catch (Exception ex) {
                    MessageBox.Show("Bad port!");
                    return;
                }
            }
        }

        public int Value
        {
            get { return value; }
            set
            {
                if (this.value != value)
                {
                    this.value = value;
                    if (this.name != null)
                        settings.SetValue(name, value);

                    if (changed != null)
                        changed(this, null);
                }
            }
        }

        public event EventHandler Changed
        {
            add
            {
                changed += value;
                if (changed != null)
                    changed(this, null);
            }
            remove
            {
                changed -= value;
            }
        }
    }
}
